package com.shuai.jit.utils;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class NoteUtil {


    // 短信app 的id
    private final static int appid = 1400503153;
    // 短信sdk 的appkey
    private final static String appkey = "50c29de0248493206049bb35cc16d33b";

    // 短信模板id
    private final static int templateId = 909379;

    // 签名的名字
    private final static String smsSign = "旅游日记";



    @Autowired
    RedisTemplate<String,String> stringRedisTemplate;

    /**
     * 随机生成6位随机验证码
     * 方法说明
     *
     * @return String
     * @Discription:扩展说明
     */
    public static String createRandomVcode() {
        //验证码
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int) (Math.random() * 9);
        }
        return vcode;
    }

    /*
     *发送手机验证码(1分钟)
     */
    public  String sendSms(String phoneNumber) {
        try {
            String verifyCode = createRandomVcode();
            String[] params = {verifyCode};
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber,
                    templateId, params, smsSign, "", "");
            log.info(String.valueOf(result.result));
            if (result.result == 0) {
                stringRedisTemplate.opsForValue().set(phoneNumber,verifyCode,1, TimeUnit.MINUTES);
                return "发送成功";
            } else {
                return "结果没出来";
            }
        } catch (HTTPException e) {
            // HTTP 响应码错误
            e.printStackTrace();
            return "响应码错误";
        } catch (JSONException e) {
            // JSON 解析错误
            e.printStackTrace();
            return "解析错误";
        } catch (IOException e) {
            // 网络 IO 错误
            e.printStackTrace();
            return "网络IO错误";
        }
    }
}
